package com.crawler.actor

import akka.actor.{Actor, ActorLogging, Props}
import com.crawler.service.DBService
import com.crawler.tables.Tables.TaskRow

/**
  * Created by tongtao.zhu on 2016/11/23.
  */
class TaskDBActor extends Actor with ActorLogging{
  val dbService = DBService.dbService
  implicit val executionContext = context.system.dispatcher

  private val isRunning = scala.collection.mutable.Map[String, Boolean]()

  override def postStop(): Unit = {
    log.info("结束一个taskDBActor")
  }

  override def preStart(): Unit = {
    // 订阅集群事件
    log.info("开始一个taskDBActor")
  }

  override def receive = {
    case task: TaskRow => {
      val flag = dbService.create(task)
      if (flag){
        isRunning(task.source ) = true
        //成功之后，创建一个actor，将task分发出去
        val dispatcheActor = context.actorOf(Props[DispatcherActor])
        dispatcheActor ! task.source
      }
    }
    case resource: String => {
      if (isRunning.contains(resource)){
        val taskGroup = dbService.findTaskGroup(resource)
        log.info(taskGroup.toString())
        sender() ! taskGroup
      }else{
        isRunning(resource) = true
        //成功之后，创建一个actor，将task分发出去
        val dispatcheActor = context.actorOf(Props[DispatcherActor])
        dispatcheActor ! resource
      }
    }
  }
}
